/*
 * @(#)AccountManager.java
 * 2011-5-9 下午09:10:34
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.platform.sysmng.exception.GsException;
import com.qyxx.platform.common.module.service.ServiceException;
import com.qyxx.platform.common.module.web.Messages;
import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.security.springsecurity.SpringSecurityUtils;
import com.qyxx.platform.common.utils.reflection.ConvertUtils;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.sysmng.accountmng.dao.AuthorityDao;
import com.qyxx.platform.sysmng.accountmng.dao.OrganizationDao;
import com.qyxx.platform.sysmng.accountmng.dao.RoleDao;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.accountmng.entity.Authority;
import com.qyxx.platform.sysmng.accountmng.entity.Organization;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.accountmng.entity.RoleJson;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.accountmng.entity.UserVo;
import com.qyxx.platform.sysmng.desktop.dao.DesktopDao;
import com.qyxx.platform.sysmng.dictmng.web.DefinitionCache;
import com.qyxx.platform.sysmng.notice.dao.CommonTypeDao;
import com.qyxx.platform.sysmng.utils.Constants;
import com.qyxx.platform.sysmng.utils.DictConstants;

/**
 * 安全相关实体的管理类, 包括用户,角色,资源与授权类.
 * 
 * @author gxj
 * @version 1.0
 * @since 1.6 2011-5-9 下午09:10:34
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class AccountManager {

	private static final String FIND_LIST_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.RoleJson(a)"
			+ " from Role a where a.resourceLevel between ? and ? and a.resourceType in (?,?) order by a.resourceLevel asc";

	// 查询同组织下所有人员
	private static final String FIND_USER_BY_ORG_CODE = "select a.id from User a inner join a.organization b where b.organizationCode like ?";

	private static Logger logger = LoggerFactory
			.getLogger(AccountManager.class);

	private UserDao userDao;
	private RoleDao roleDao;
	private DesktopDao desktopDao;
	private AuthorityDao authorityDao;
	private OrganizationDao organizationDao;
	private Md5PasswordEncoder md5 = new Md5PasswordEncoder();
	private CommonTypeDao commonTypeDao;
	// -- User Manager --//
	@Transactional(readOnly = true)
	public User getUser(Long id) {
		User user = userDao.get(id);
		List<Role> rolelist = user.getRoleList();
		StringBuffer s = new StringBuffer();
		for (int i = 0, length = rolelist.size(); i < length; i++) {
			String name = rolelist.get(i).getRoleName();
			if (i > 0) {
				s.append(",");
			}
			s.append(name);
		}
		user.setRoleName(s.toString());
		return user;
	}

	/**
	 * 保存用户
	 * 
	 * @param entity
	 * @param rids
	 */
	public void saveUser(User entity, String rids) {
		setAutoUserCode(entity);
		userDao.save(entity);
		Long newuserId = entity.getId();
		if (StringUtils.isNotBlank(rids)) {
		roleDao.deleteUserList(newuserId);
		String ids[] = rids.split(",");
		for (String x : ids) {
			Long id = Long.valueOf(x);
			roleDao.save(newuserId, id);
		}
		}else{
			roleDao.deleteUserList(newuserId);
		}
		
	}
	
	/**
	 * 设置自动员工号
	 * 
	 * @param entity
	 */
	public void setAutoUserCode(User entity) {
		String userCode = entity.getEmployeeId();
		if(StringUtils.isNotBlank(userCode)) {
			//检查员工号是否重复
			if(!userDao.checkUnique(userCode, entity.getId())) {
				throw new ServiceException("员工号"+userCode+"已经存在，请重新输入");
			}
		} else {
			String enableAutoCode = DefinitionCache.getValueByKey(DictConstants.SYS_PARAMS_KEY, DictConstants.SYS_PARAMS_KEY_USER_AUTOCODE_ENABLE);
			if(DictConstants.ENABLE.equalsIgnoreCase(enableAutoCode)) { //开启自动编号功能
				//生成员工号
				String maxCode = userDao.getMaxAutoIdNo("User", "employeeId", "");
				Integer val = 1;
				if(StringUtils.isNotBlank(maxCode)) {
					val = NumberUtils.toInt(maxCode, 0) + 1;
				}
				String len = DefinitionCache.getValueByKey(DictConstants.SYS_PARAMS_KEY, DictConstants.SYS_PARAMS_KEY_USER_CODE_BIT);
				len = org.apache.commons.lang3.StringUtils.defaultIfBlank(len, DictConstants.DEFAULT_USER_CODE_BIT);
				userCode = StringUtils.leftPad(String.valueOf(val), Integer.valueOf(len), "0");
				entity.setEmployeeId(userCode);
			}
		}
		
	}
	
	/**
	 * 保存用户信息
	 * 
	 * @param entity
	 */
	public void saveUserInfo(User entity) {
		setAutoUserCode(entity);
		userDao.save(entity);	
	}
	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户",
					SpringSecurityUtils.getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		User user = this.getUser(id);
		user.setStatus(Constants.NO_USING);

	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Long id) {
		return id == 1;
	}

	/**
	 * 使用属性过滤条件查询用户.
	 */
	@Transactional(readOnly = true)
	public Page<User> searchUser(final Page<User> page,
			final List<PropertyFilter> filters) {
		return userDao.findPage(page, filters);
	}

	/**
	 * 使用属性过滤条件查询角色.
	 */
	@Transactional(readOnly = true)
	public Page<Role> searchRole(final Page<Role> page,
			final List<PropertyFilter> filters) {
		return roleDao.findPage(page, filters);
	}

	@Transactional(readOnly = true)
	public User findUserByLoginName(String loginName) {
		List<PropertyFilter> pfList = new ArrayList<PropertyFilter>();
		PropertyFilter pf = new PropertyFilter("EQS_loginName_OR_mobilePhone_OR_email", loginName);
		pfList.add(pf);
		List<User> userList = userDao.find(pfList);
		if(userList!=null && !userList.isEmpty()) {
			if(userList.size() == 1) {
				return userList.get(0);
			} else {
				throw new GsException("存在多个登录账户，请检查登录账户是否设置正确");
			}
		} else {
			return null;
		}
		//return userDao.findUniqueBy("loginName", loginName);
	}

	/**
	 * 检查用户名是否唯一.
	 * 
	 * @return loginName在数据库中唯一或等于oldLoginName时返回true.
	 */
	@Transactional(readOnly = true)
	public boolean isLoginNameUnique(String newLoginName,
			String oldLoginName) {
		return userDao.isPropertyUnique("loginName", newLoginName,
				oldLoginName);
	}

	// -- Role Manager --//
	@Transactional(readOnly = true)
	public Role getRole(Long id) {
		Role role = roleDao.get(id);
		role.setUserIds(ConvertUtils.convertElementPropertyToString(
				role.getUserList(), "id", ","));
		role.setSeeUserIds(ConvertUtils.convertElementPropertyToString(
				role.getSeeUserList(), "id", ","));
		return role;
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRole() {
		return roleDao.getAll("id", true);
	}

	@Transactional(readOnly = true)
	public List<User> getAllUser() {
		return userDao.getAll();
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRoleWithLoadAuthority() {
		List<Role> roleList = roleDao.getAll("id", true);
		for (Role role : roleList) {
			roleDao.initProxyObject(role.getAuthorityList());
			/*
			 * List<Authority> authList = role.getAuthorityList(); for(Authority
			 * auth : authList) { auth.getResourceUrl(); }
			 */
		}
		return roleList;
	}

	/**
	 * 保存角色与权限,个人桌面的关系
	 * 
	 * @param entity
	 * @param aids
	 * @param desktopIds
	 * @param systemTypeIds--系统分类ID
	 * @param seeUserIds--可见用户ID
	 */
	public void saveRole(Role entity, String aids,String desktopIds,String systemTypeIds, String seeUserIds) {
		roleDao.save(entity);
		Long roleId = entity.getId();// 获取保存的角色ID
		
		authorityDao.deleteByRoleId(roleId);
		if (StringUtils.isNotBlank(aids)) {
			String ids[] = aids.split(",");
			for (String x : ids) {
				Long id = Long.valueOf(x);
				authorityDao.save(roleId, id);// 在角色和权限的关联表中插入数据
			}
		}		
		//向SYS_DESKTOP_TO_ROLE关系表中添加关联关系	
		desktopDao.deleteDesktopId(entity.getId());//先删除关联表中桌面和角色的记录
		if (StringUtils.isNotBlank(desktopIds)) {//再添加记录
               String dIds[] = desktopIds.split(",");
			for (String desktopId : dIds) {
				Long dId = Long.valueOf(desktopId);
				desktopDao.saveDesktopRoles(dId, entity.getId());
			}
		} 		
		commonTypeDao.deleteByRoleId(roleId);
		if (StringUtils.isNotBlank(systemTypeIds)) {
			String ids[] = systemTypeIds.split(",");
			for (String x : ids) {
				Long id = Long.valueOf(x);
				commonTypeDao.saveCommonTypes(id, roleId);
			}
		}
		//保存角色可见用户关系
		authorityDao.deleteRoleSeeUserByRoleId(roleId);
		if (StringUtils.isNotBlank(seeUserIds)) {
			String ids[] = seeUserIds.split(",");
			for (String x : ids) {
				Long id = Long.valueOf(x);
				authorityDao.saveRoleSeeUser(roleId, id);// 在角色和权限的关联表中插入数据
			}
		}
		
	}
	
	/**
	 * 保存角色与用户及权限的关系
	 * 
	 * @param entity
	 * @param aids
	 * @param uids
	 * @param desktopIds
	 * @param systemTypeIds
	 * @param seeUserIds
	 */
	public void saveUserAndRole(Role entity, String aids, String uids,String desktopIds,String systemTypeIds, String seeUserIds) {
		roleDao.save(entity);
		Long roleId = entity.getId();// 获取保存的角色ID
		authorityDao.deleteByRoleId(roleId);
		if (StringUtils.isNotBlank(aids)) {
			String ids[] = aids.split(",");
			for (String x : ids) {
				Long id = Long.valueOf(x);
				authorityDao.save(roleId, id);// 在角色和权限的关联表中插入数据
			}
		}
		roleDao.deleteRoleList(roleId);
		if (StringUtils.isNotBlank(uids)) {
			String userids[] = uids.split(",");
			for (String x : userids) {
				Long id = Long.valueOf(x);
				roleDao.save(id, roleId);
			}// 在角色和用户的关联表中插入数据
		}
		//向SYS_DESKTOP_TO_ROLE关系表中添加关联关系	
		desktopDao.deleteDesktopId(entity.getId());//先删除关联表中桌面和角色的记录
		if (StringUtils.isNotBlank(desktopIds)) {//再添加记录
               String dIds[] = desktopIds.split(",");
			for (String desktopId : dIds) {
				Long dId = Long.valueOf(desktopId);
				desktopDao.saveDesktopRoles(dId, entity.getId());
			}
		} 
		commonTypeDao.deleteByRoleId(roleId);
		if (StringUtils.isNotBlank(systemTypeIds)) {
			String ids[] = systemTypeIds.split(",");
			for (String x : ids) {
				Long id = Long.valueOf(x);
				commonTypeDao.saveCommonTypes(id, roleId);
			}
		}
		//保存角色可见用户关系
		authorityDao.deleteRoleSeeUserByRoleId(roleId);
		if (StringUtils.isNotBlank(seeUserIds)) {
			String ids[] = seeUserIds.split(",");
			for (String x : ids) {
				Long id = Long.valueOf(x);
				authorityDao.saveRoleSeeUser(roleId, id);// 在角色和权限的关联表中插入数据
			}
		}
	}

	public void deleteRole(Long id) {
		Role role = this.getRole(id);
		role.setRoleStatus(Constants.NO_USING);
	}

	// -- Authority Manager --//
	@Transactional(readOnly = true)
	public List<Authority> getAllAuthority() {
		return authorityDao.getAll();
	}

	@Transactional(readOnly = true)
	public List<Authority> getAllUsingAuthorityWithLoadRole() {
		List<Authority> authList = authorityDao.findBy(
				"resourceStatus", Constants.IS_USING);
		for (Authority auth : authList) {
			authorityDao.initProxyObject(auth.getRoleList());
		}
		return authList;
	}

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Autowired
	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}

	@Autowired
	public void setDesktopDao(DesktopDao desktopDao) {
		this.desktopDao = desktopDao;
	}
	
	@Autowired
	public void setCommonTypeDao(CommonTypeDao commonTypeDao) {
			this.commonTypeDao = commonTypeDao;
	}
	 
	/**
	 * 
	 * 根据组织id查看其所有的子组织id并拼装成字符串
	 * 
	 * @param orgId
	 * @return
	 */
	public String getStringOrgSonId(Long orgId) {
		String orgids = String.valueOf(orgId);
		Organization org = this.organizationDao.get(orgId);
		orgids += this.getStringOrgbyObj(org);
		return orgids;
	}

	public String getStringOrgbyObj(Organization org) {
		String orgIds = "";
		List<Organization> orgList = org.getOrganizationList();
		if (orgList != null && orgList.size() > 0) {
			for (Organization organization : orgList) {
				orgIds += "," + organization.getId();
				orgIds += this.getStringOrgbyObj(organization);
			}

		}
		return orgIds;
	}

	/**
	 * 
	 * 根据组织编码Code查看其所有的上级组织下的角色集合
	 * 
	 */
	@Transactional(readOnly = true)
	public List<RoleJson> getRoleList(Long newid) {
		Organization org = organizationDao.get(newid);
		String code = org.getOrganizationCode();// 获得当前组织编码
		StringBuffer temp = new StringBuffer();
		for (int i = 3; i <= code.length(); i = i + 3) {
			String a = code.substring(0, i);
			if (i > 3) {
				temp.append(",");
			}
			temp.append(a);
		}

		String codedemo = temp.toString();

		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter propertyFilterParentOrg = new PropertyFilter(
				"INS_organizationCode", codedemo);

		filters.add(propertyFilterParentOrg);

		List<Organization> orgList = organizationDao.find(filters);
		// 获得当前组织的所有上级组织的集合

		List<RoleJson> list = new ArrayList<RoleJson>();
		for (int i = 0; i < orgList.size(); i++) {
			Organization org1 = orgList.get(i);
			Long orgId = orgList.get(i).getId();
			String name = orgList.get(i).getOrganizationName();

			RoleJson rj = new RoleJson(orgId, name, org1);
			rj.setIdNum(orgId);
			rj.setNocheck(true);
			list.add(rj);// 将组织添加到集合中

			List<PropertyFilter> newfilters = PropertyFilter
					.buildFromHttpRequest(Struts2Utils.getRequest());
			PropertyFilter idFilter = new PropertyFilter(
					"EQL_organization.id", String.valueOf(orgId));
			newfilters.add(idFilter);
			PropertyFilter statusFilter = new PropertyFilter(
					"EQS_roleStatus", Constants.IS_USING);
			newfilters.add(statusFilter);

			List<Role> roleList = roleDao.find(newfilters);// 根据组织ID，查找对应的角色集合

			for (int j = 0; j < roleList.size(); j++) {

				Long roleid = roleList.get(j).getId();
				String roleName = roleList.get(j).getRoleName();

				RoleJson rj1 = new RoleJson(roleid, roleName, orgId);
				rj1.setIdNum(roleid);
				list.add(rj1);// 将角色添加到集合中
			}

		}

		return list;

	}

	/**
	 * 
	 * 根据用户ID查看其已选择的角色集合
	 * 
	 */
	@Transactional(readOnly = true)
	public List<RoleJson> getSelectedRole(Long userId) {
		Organization org = userDao.get(userId).getOrganization();
		String code = org.getOrganizationCode();// 获得当前组织编码

		StringBuffer temp = new StringBuffer();
		for (int i = 3; i <= code.length(); i = i + 3) {
			String a = code.substring(0, i);
			if (i > 3) {
				temp.append(",");
			}
			temp.append(a);
		}
		String codedemo = temp.toString();

		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter propertyFilterParentOrg = new PropertyFilter(
				"INS_organizationCode", codedemo);

		filters.add(propertyFilterParentOrg);

		List<Organization> orgList = organizationDao.find(filters);
		// 获得当前组织的所有上级组织的集合

		List<RoleJson> list = new ArrayList<RoleJson>();

		for (int i = 0; i < orgList.size(); i++) {
			Organization org1 = orgList.get(i);
			Long orgId = orgList.get(i).getId();
			String name = orgList.get(i).getOrganizationName();
			RoleJson rj = new RoleJson(orgId, name, org1);
			rj.setNocheck(true);
			list.add(rj);
			List<PropertyFilter> newfilters = PropertyFilter
					.buildFromHttpRequest(Struts2Utils.getRequest());
			PropertyFilter oidFilter = new PropertyFilter(
					"EQL_organization.id", String.valueOf(orgId));
			newfilters.add(oidFilter);
			PropertyFilter statusFilter = new PropertyFilter(
					"EQS_roleStatus", Constants.IS_USING);
			newfilters.add(statusFilter);

			List<Role> roleList = roleDao.find(newfilters);// 根据组织ID，查找其下所有角色集合

			List<Role> srole = userDao.get(userId).getRoleList();// 根据用户ID，查找其下拥有角色集合

			for (int j = 0; j < roleList.size(); j++) {
				Long org_id = roleList.get(j).getOrganization()
						.getId();
				Long roleid = roleList.get(j).getId();
				String rolename = roleList.get(j).getRoleName();
				RoleJson rjk = new RoleJson(roleid, rolename, org_id);
				for (int k = 0; k < srole.size(); k++) {
					if (srole.get(k).getId() == roleid) {
						rjk.setChecked(true);
					}
				}
				list.add(rjk);
			}
		}
		return list;
	}
	
	/**
	 * 查询当前用户所有的角色，选中已有角色
	 * 
	 * @param userId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<RoleJson> getAllSelectedRoleOld(Long userId) {
		List<Organization> orgList = organizationDao.getAll();
		List<RoleJson> list = new ArrayList<RoleJson>();
		for (int i = 0; i < orgList.size(); i++) {
			Organization org1 = orgList.get(i);
			Long orgId = orgList.get(i).getId();
			String name = orgList.get(i).getOrganizationName();
			RoleJson rj = new RoleJson(orgId, name, org1);
			rj.setNocheck(true);
			list.add(rj);
			List<PropertyFilter> newfilters = PropertyFilter
					.buildFromHttpRequest(Struts2Utils.getRequest());
			PropertyFilter oidFilter = new PropertyFilter(
					"EQL_organization.id", String.valueOf(orgId));
			newfilters.add(oidFilter);
			PropertyFilter statusFilter = new PropertyFilter(
					"EQS_roleStatus", Constants.IS_USING);
			newfilters.add(statusFilter);
			List<Role> roleList = roleDao.find(newfilters);// 根据组织ID，查找其下所有角色集合
			List<Role> srole = null; 
			if(userId != null)
				srole =	userDao.get(userId).getRoleList();// 根据用户ID，查找其下拥有角色集合
			for (int j = 0; j < roleList.size(); j++) {
				Long org_id = roleList.get(j).getOrganization()
						.getId();
				Long roleid = roleList.get(j).getId();
				String rolename = roleList.get(j).getRoleName();
				RoleJson rjk = new RoleJson(roleid, rolename, org_id);
				if(srole != null) {
					for (int k = 0; k < srole.size(); k++) {
						if (srole.get(k).getId() == roleid) {
							rjk.setChecked(true);
						}
					}
				}
				list.add(rjk);
			}
		}
		return list;
	}
	
	/**
	 * 查询当前用户所有的角色，选中已有角色
	 * 优化性能  2016-04-14 bob
	 * @param userId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<RoleJson> getAllSelectedRole(Long userId) {
		//List<Organization> orgList = organizationDao.getAll();
		
		List<RoleJson> list = new ArrayList<RoleJson>();
		
		/*for (int i = 0; i < orgList.size(); i++) {
			Organization org = orgList.get(i);
			Long orgId = org.getId();
			String name = org.getOrganizationName();
			RoleJson rj = new RoleJson(orgId, name, org);
			rj.setNocheck(true);
			list.add(rj);
		}*/
		
		List<PropertyFilter> newfilters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter statusFilter = new PropertyFilter(
				"EQS_roleStatus", Constants.IS_USING);
		newfilters.add(statusFilter);
		List<Role> roleList = roleDao.find(newfilters);
		
		List<Long> roleIds = null; 
		if(userId != null) {
			roleIds = new ArrayList<Long>();
			List<Role> srole = userDao.get(userId).getRoleList();// 根据用户ID，查找其下拥有角色集合
			for (int k = 0; k < srole.size(); k++) {
				roleIds.add(srole.get(k).getId());
			}
		}
		
		for (int j = 0; j < roleList.size(); j++) {
			Long org_id = roleList.get(j).getOrganization()
					.getId();
			Long roleid = roleList.get(j).getId();
			String rolename = roleList.get(j).getRoleName();
			RoleJson rjk = new RoleJson(roleid, rolename, org_id);
			if(roleIds != null && roleIds.contains(roleid)) {
				rjk.setChecked(true);
			}
			list.add(rjk);
		}
		return list;
	}

	public List<RoleJson> getList(Long userId) {
		return getList(userId,true);
	}

	/**
	 * 根据用户所属组织查询组织下其他组织信息
	 * 
	 * @param userId
	 * @param isAppendRole
	 * @return
	 */
	public List<RoleJson> getList(Long userId, Boolean isAppendRole) {
		List<RoleJson> list = new ArrayList<RoleJson>();
		Organization org = userDao.get(userId).getOrganization();
		String code = org.getOrganizationCode();// 获得当前组织编码
		/*List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter idFilter = new PropertyFilter(
				"LIKES_organizationCode", code + "%");
		filters.add(idFilter);
		List<Organization> orgList = organizationDao.find(filters);*/
		List<Organization> orgList = organizationDao.findOrgList(code);
		// 根据组织编码查找其所有下级组织集合

		for (int i = 0; i < orgList.size(); i++) {
			Organization org1 = orgList.get(i);
			Long orgId = org1.getId();
			String name = org1.getOrganizationName();

			RoleJson rj = new RoleJson(orgId, name, org1);
			/*
			 * if(null!=org1.getOrganization()) { Long parentId =
			 * org1.getOrganization().getId(); rj.setOrgId(parentId); }
			 * rj.setOpen(true); rj.setIdNum(orgId); rj.setIconSkin("icon01");
			 */
			list.add(rj);// 将组织添加到集合中
			
		}
		
		if (isAppendRole) {
			List<PropertyFilter> newfilters = PropertyFilter
					.buildFromHttpRequest(Struts2Utils
							.getRequest());
			/*PropertyFilter oidFilter = new PropertyFilter(
					"EQL_organization.id", String.valueOf(orgId));
			newfilters.add(oidFilter);*/
			PropertyFilter statusFilter = new PropertyFilter(
					"EQS_roleStatus", Constants.IS_USING);
			newfilters.add(statusFilter);

			List<Role> roleList = roleDao.find(newfilters);// 根据组织ID，查找对应的角色集合

			for (int j = 0; j < roleList.size(); j++) {
				Role role = roleList.get(j);
				Long roleid = role.getId();
				String roleName = role.getRoleName();
				Long orgId = role.getOrganization().getId();
				RoleJson rj1 = new RoleJson(roleid, roleName,
						orgId);
				/*
				 * rj1.setOrgId(orgId); rj1.setIdNum(roleid);
				 * rj1.setIconSkin("icon03");
				 */
				list.add(rj1);// 将角色添加到集合中
			}
		}
		
		return list;
	}
	/**
	 * 修改密码
	 */
	public void updatePassWord(String oldPass, String newPass,Long uId) {
		User user = userDao.get(uId);
		String oldPassMd5 = md5.encodePassword(oldPass,
				user.getLoginName());
		if (user.getPassword().equals(oldPassMd5)) {
			user.setPassword(md5.encodePassword(newPass,
					user.getLoginName()));
		} else {
			throw new ServiceException("输入的旧密码错误");
		}
	}
	/**
	 * 修改个人信息
	 */
	public void updateUserInfo(User user) {
		User newUser = userDao.get(user.getId());
		newUser.setRealName(user.getRealName());
		newUser.setNickname(user.getNickname());
		newUser.setEmail(user.getEmail());
		newUser.setMobilePhone(user.getMobilePhone());
	}
	/**
	 * 重置密码
	 */
	public void resetPass(Long[] userIds, String password, Long orgId) {
		PropertyFilter pf = null;
		if(userIds != null && userIds.length > 0) {//根据用户ID查询数据
			pf = new PropertyFilter("INL_id", StringUtils.join(userIds));
		} else {//根据组织ID重置密码
			if (orgId != null) {
				String code = this.findOrganization(orgId).getOrganizationCode();
				pf = new PropertyFilter(
						"LIKELS_com.qyxx.platform.sysmng.accountmng.entity.Organization$$$organization.organizationCode", code);
			}
		}
		if(pf != null) {//批量查询数据
			List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
			filters.add(pf);
			List<User> userList = this.userDao.find(filters);
			if(userList != null) {
				for(User user : userList) {
					user.setPassword(md5.encodePassword(password,user.getLoginName()));
				}
			}
		}
	}
	/**
	 * 查找同组织下所有人员
	 * 
	 * @param orgCode
	 * @return
	 */
	public List<Long> findUserInSameOrg(String orgCode) {
		List<Long> list = userDao.find(FIND_USER_BY_ORG_CODE, orgCode
				+ "%");
		return list;
	}
	
	/**
	 * 查找所有用户，用于显示创建者
	 * 
	 * @return
	 */
	public Map<Long, UserVo> getUsers(){
		List<User> users=userDao.getAll();
		Map<Long, UserVo> map=new HashMap<Long, UserVo>();
		for(User user:users){
			UserVo uv=new UserVo();
			uv.setId(user.getId());
			uv.setLoginName(user.getLoginName());
			uv.setNickName(user.getNickname());
			uv.setOrgName(user.getOrganizationName());
			uv.setRealName(user.getRealName());
			map.put(user.getId(), uv);
		}
		return map;
		
	}
	/**
	* 根据类型来返回上级组织或者下级组织的所有用户
	*/
	public List<RoleJson> getUserByOrganization(User crrentUser,String type){
		List<RoleJson> list = new ArrayList<RoleJson>();
		List<Organization> orgList = new ArrayList<Organization>();
		Organization org = crrentUser.getOrganization();
		String code = org.getOrganizationCode();// 获得当前用户的组织编码
		if(type.equals("shangji")){
			// 根据组织编码查找其所有上级组织集合
			StringBuffer temp = new StringBuffer();
			for (int i = 3; i <= code.length(); i = i + 3) {
				String a = code.substring(0, i);
				if (i > 3) {
					temp.append(",");
				}
				temp.append(a);
			}
			String codedemo = temp.toString();
			List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"INS_organizationCode", codedemo);
			filters.add(propertyFilterParentOrg);
			orgList = organizationDao.find(filters);	
		}else if(type.equals("xiaji")){			
			// 根据组织编码查找其所有下级组织集合
			List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
			PropertyFilter idFilter = new PropertyFilter(
					"LIKES_organizationCode", code + "%");
			filters.add(idFilter);
			orgList = organizationDao.find(filters);		
		}
		if(orgList.size()>0){
			for (Organization org1 : orgList) {
				Long orgId = org1.getId();
				String name = org1.getOrganizationName();
				RoleJson rj = new RoleJson(orgId, name, org1);
				rj.setNocheck(true);
				list.add(rj);// 将组织添加到集合中

				List<PropertyFilter> newfilters = new ArrayList<PropertyFilter>();
				PropertyFilter oidFilter = new PropertyFilter(
					"EQL_organization.id", String.valueOf(orgId));
				newfilters.add(oidFilter);
				PropertyFilter statusFilter = new PropertyFilter(
					"EQS_status", Constants.IS_USING);
				newfilters.add(statusFilter);
				List<User> userList = userDao.find(newfilters);// 根据组织ID，查找对应的用户集合
				for (User user : userList) {
					RoleJson rj1 = new RoleJson(user);		
					list.add(rj1);// 将用户添加到集合中
				}
			}
			return list;
		}
		return null;
		
	}
	public Boolean validateRole(String roleName,Long id) {
		//List<Role> list = new ArrayList<Role>();
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		PropertyFilter nameFilter = new PropertyFilter("EQS_roleName", roleName);
		filters.add(nameFilter);
		if(id!=null){//修改
			PropertyFilter idFilter = new PropertyFilter("NEL_id",String.valueOf(id));
			filters.add(idFilter);
		}
	
		List<Role> list = roleDao.find(filters);
		if(list.size()>0){
			return false;
		}
		return true;
	}
	
	/**
	 * 变更员工姓名
	 * 
	 * @param userId
	 * @param employeeName
	 */
	public void changeEmployeeName(Long userId, String employeeName) {
		User user = userDao.get(userId);
		if (user!=null) {
			user.setNickname(employeeName);
		} else {
			throw new ServiceException("用户不存在，变更员工姓名失败");
		}
	}

	/**
	 * 启用/禁用用户
	 * 
	 * @param userId
	 * @param employeeName
	 */
	public void changeStatus(Long userId, String status) {
		User user = userDao.get(userId);
		if (user!=null) {
			user.setStatus(status);
		} else {
			throw new ServiceException("用户不存在，启用/禁用用户失败");
		}
	}
	
	/**
	 * 获取组织
	 * 
	 * @return
	 */
	public Organization findOrganization(Long orgId) {
		return organizationDao.get(orgId);
	}
	
	/**
	 * 获取角色列表
	 * 
	 * @param filters
	 * @return
	 */
	public List<Role> findRoleList(List<PropertyFilter> filters) {
		return roleDao.find(filters);
	}
	
	/**
	 * 获取用户列表
	 * 
	 * @param filters
	 * @return
	 */
	public List<User> findUserList(List<PropertyFilter> filters) {
		return userDao.find(filters);
	}
}
